package cn.yunyichina.provider.pay.alipay.service;

import cn.yunyichina.provider.pay.alipay.config.Alipay;
import cn.yunyichina.provider.pay.alipay.entity.AlipayRefundResponse;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.NumberUtil;
import com.alipay.api.domain.TradeFundBill;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by Lullaby on 2016/12/26.
 */
public class BaseRefundService extends BaseTradeService {

    protected AlipayRefundResponse buildAlipayRefundResponse(AlipayTradeRefundResponse refundResponse) {
        AlipayRefundResponse alipayRefundResponse = new AlipayRefundResponse();

        alipayRefundResponse.setPlatformOrderNo(refundResponse.getOutTradeNo());
        alipayRefundResponse.setPlatformSerialNumber(NumberUtil.buildPaymentDealNo());
        alipayRefundResponse.setPayTransactionId(refundResponse.getTradeNo());
//        alipayRefundResponse.setRefundAmount(String.valueOf(new BigDecimal(refundResponse.getRefundFee()).multiply(new BigDecimal(100)).intValue()));
        alipayRefundResponse.setDealAccount(refundResponse.getBuyerUserId());
        alipayRefundResponse.setRefundTime(DateUtils.dateToString(refundResponse.getGmtRefundPay()));

        List<TradeFundBill> refundDetailItemList = refundResponse.getRefundDetailItemList();
        alipayRefundResponse.setRefundAmount("0");
        if (!CollectionUtils.isEmpty(refundDetailItemList)) {
            for (TradeFundBill tradeFundBill : refundDetailItemList) {
                switch (Alipay.FundChannel.valueOf(tradeFundBill.getFundChannel())) {
                    case ALIPAYACCOUNT:
                        alipayRefundResponse.setRefundAmount(new BigDecimal(tradeFundBill.getAmount()).multiply(new BigDecimal(100)).toString());
                        break;
                    case OUTSIDECARD:
                        alipayRefundResponse.setInsuranceAmount(new BigDecimal(tradeFundBill.getAmount()).multiply(new BigDecimal(100)).toString());
                        break;
                    default:
                        alipayRefundResponse.setRefundAmount(new BigDecimal(tradeFundBill.getAmount()).multiply(new BigDecimal(100)).toString());
                        break;
                }
            }
        } else {

        }

        return alipayRefundResponse;
    }

}
